<template>
  <div class="root">
    <div class="top">
      <div class="image">
        <img src="../../assets/images/首页logo.png"/>
      </div>
      <div class="font">
        <span class="font2">医生后台管理</span>
        <span class="font3">设置预约人数</span>
        <span class="font4" @click="$router.push({path:'/showuser',query:{did}})">查看消息</span>
        <span class="font4" @click="vis_doc=true">返回首页</span>
      </div>
      <div class="login" v-if="!doctoken">
        <span class="login-hover" @click="login">登录</span>
        <!-- <span class="login-hover" @click="register">注册</span> -->
      </div>
      <div class="login" v-else>
        <span>{{ user.account }}</span>
        <span class="login-hover" @click="vis_logout=true">退出登录</span>
      </div>
    </div>
    <div class="mid">
      <el-card>
        <div class="content">
          <div class="morning">
            <span>当前上午预约人数：{{ cur_morning }}人</span>
            <span style="margin-left: 100px;margin-right: 20px;">设置明日上午预约人数：</span>
            <el-input-number v-model="num_morning" :min="0" :max="50" style="width: 140px;"/>
            <el-button type="success" style="margin-left: 10px;"@click="handleChange">确认</el-button>
          </div>
          <div class="morning">
            <span>当前下午预约人数：{{ cur_afternoon }}人</span>
            <span style="margin-left: 100px;margin-right: 20px;;">设置明日下午预约人数：</span>
            <el-input-number v-model="num_afternoon" :min="0" :max="50" style="width: 140px;"/>
            <el-button type="success" style="margin-left: 10px;" @click="handleChange">确认</el-button>
          </div>
        </div>
      </el-card>
    </div>
  </div>

  <!-- 医生登录对话框 -->
  <el-dialog v-model="visible_login_doc" title="医生登录" width="600px">
    <el-form :model="user" :rules="rules_login" ref="form_login_doc">
      <div class="user">
        <p class="user-account">账号:</p>
        <el-form-item class="input" prop="account">
          <el-input style="width: 300px;font-size: 18px;" 
          size="small" v-model="user.account"
          placeholder="请输入用户名"></el-input>
        </el-form-item>
      </div>

      <div class="user">
        <p class="user-account">密码:</p>
        <el-form-item class="input" prop="password">
          <el-input style="width: 300px;font-size: 18px;" 
          size="small" v-model="user.password" type="password"
          placeholder="请输入密码"></el-input>
        </el-form-item>
      </div>
    </el-form>
    <!-- <span class="forget" @click="changeForget">忘记密码？点击重置</span> -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible_login_doc = false">取消</el-button>
        <el-button type="primary" @click="subLogin('医生')">
          登录
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 退出登录确认对话框 -->
  <el-dialog
    v-model="vis_logout"
    width="500px"
    style="height: 3000px;">
    <span style="font-size:22px;margin-left: 20px;">确认退出吗？</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="vis_logout=false">取消</el-button>
        <el-button type="primary" @click="logout">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 首次登录重置密码 -->
  <el-dialog
    v-model="vis_change"
    width="500px">
    <span style="font-size:22px;margin-left: 20px;">密码为初始密码，是否重置密码？</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="vis_change=false" type="danger">取消</el-button>
        <el-button type="success" @click="vis_change=false,vis_reset=true">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 重置密码 -->
  <el-dialog
    v-model="vis_reset"
    width="500px"
    title="重置密码（重置后需要重新登陆）">
    <el-form :model="user_reset" :rules="rules_reset" ref="form_reset">
      <div class="user">
        <p class="user-account">新密码:</p>
        <el-form-item class="input" prop="password">
          <el-input style="width: 300px;font-size: 18px;" 
          size="small" v-model="user_reset.password" type="password"
          placeholder="请输入新密码"></el-input>
        </el-form-item>
      </div>

      <div class="user">
        <p class="user-account">确认密码:</p>
        <el-form-item class="input" prop="confirm">
          <el-input style="width: 300px;font-size: 18px;margin-left: -20px;" 
          size="small" v-model="user_reset.confirm" type="password"
          placeholder="请重新输入密码"></el-input>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="vis_change=false" type="danger">取消</el-button>
        <el-button type="success" @click="changePassword">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 医生返回首页提示框 -->
  <el-dialog
    v-model="vis_doc"
    width="500px">
    <span style="font-size:22px;margin-left: 20px;">下次进入需要重新登陆，是否返回？</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="vis_doc=false" type="danger">取消</el-button>
        <el-button type="success" @click="confirm()">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup>
import { onMounted,ref,reactive,nextTick, onBeforeUnmount } from 'vue';
import { reqdocLogin,reqdocReset,reqCurrentNum,reqhandleChange } from "@/api/doctor";
import { useRouter } from 'vue-router';
import { useChatStore } from '@/store/message';

const chatStore=useChatStore()

const $router=useRouter()

let did=ref()//医生id

let socket=null

let message=ref()//存储单条消息

// 判断是否是JSON消息
const isJSON=(str)=>{
  try{
    JSON.parse(str)
    return true
  }catch(e){
    return false
  }
}

// 连接socket
const handleMessage=async ()=>{
  did.value=localStorage.getItem('DOCTORID')
  if(!socket){
    socket = new WebSocket(`ws://47.108.153.130:8090/consultation/false/${did.value}`); // 使用WebSocket协议
  }

  socket.onopen = () => {
    console.log('连接成功');
  };

  socket.onerror = (error) => {
    console.error('WebSocket 错误:', error);
  };

  socket.onclose = () => {
    console.log('连接关闭');
  };
  // 监听服务端发送的消息
  socket.onmessage = (event) => {
    console.log('收到消息:', event.data);
    message.value=event.data
    if(isJSON(message.value)){
      message.value=JSON.parse(message.value)
    }
    chatStore.addMessage(message.value.sender,message.value)
  };
}

// 设置明日预约人数
let num_morning=ref(0)
let num_afternoon=ref(0)

// 当前预约人数
let cur_morning=ref()
let cur_afternoon=ref()

const doctoken=ref()

onMounted(async ()=>{
  visible_login_doc.value=true
  doctoken.value=localStorage.getItem('DOCTOKEN')
  user.account=localStorage.getItem('DOCNAME')
  did.value=localStorage.getItem('DOCTORID')
  let res=await reqCurrentNum(did.value)
    // console.log(res)
  //防止刷新丢失预约人数 
  if(res.data.code){
    cur_morning.value=res.data.data.nowAmNum
    cur_afternoon.value=res.data.data.nowPmNum
  }
  // 防止刷新丢失设置的预约人数
  const people=JSON.parse(localStorage.getItem('PEOPLE'))
  // console.log(people)
  num_morning.value=people?.am
  num_afternoon.value=people?.pm
  // 登录状态下防止刷新断连
  if(localStorage.getItem('DOCTOKEN')){
    handleMessage()
  }
})

onBeforeUnmount(()=>{
  chatStore.saveState()
})

// 是否重置密码
let vis_change=ref(false)
let vis_reset=ref(false)

// 控制登录对话框显示
let visible_login_doc=ref(false)
// 退出登录提示对话框
let vis_logout=ref(false)
const logout=()=>{
  vis_logout.value=false
  doctoken.value=''
  // localStorage.removeItem('DOCTOKEN')
  localStorage.clear()
  socket.close()
}

// 存储登录时用户输入的账号和密码
let user=reactive({
  account:'',
  password:'',
})

// 登录表单实例
let form_login_doc=ref()

// 登录前清空
const login=async ()=>{
  user.account=''
  user.password=''
  visible_login_doc.value=true
  await nextTick(() => {
    form_login_doc.value.resetFields();  // 只有在 form_login 已经赋值后才能调用 resetFields
  });
}

//用户名校验 
const validateUsername = (rule, value, callback) => {
  const usernamePattern = /^[A-Za-z0-9\u4e00-\u9fa5]{1,10}$/; // 匹配字母、数字和汉字，长度在1到10之间
  if (!value) {
    callback(new Error('用户名不能为空'));
  } else if (!usernamePattern.test(value)) {
    callback(new Error('用户名只能包含字母、数字或汉字，且长度在1到10之间'));
  } else {
    callback();
  }
};
//用户密码校验
const validatePassword = (rule, value, callback) => {
  // const passwordPattern = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,10}$/; // 只能包含字母或数字，长度在8到10之间
  if (!value) {
    callback(new Error('密码不能为空'));
  } else {
    callback();
  }
};
//登录校验规则 
const rules_login={

  account:[{trigger:'blur'},
  {validator:validateUsername,trigger:'blur'}],

  password:[{trigger:'blur'},
  {validator:validatePassword,trigger:'blur'}]

}
// 点击登录
const subLogin=async (value)=>{
  await form_login_doc.value.validate()
  visible_login_doc.value = false
  let res=await reqdocLogin(user.account,user.password)
  console.log(res)
  console.log(user.account,user.password)
  if(res.data.code){
    localStorage.setItem('DOCTOKEN',res.data.data.token)
    localStorage.setItem('DOCTORID',res.data.data.did)
    localStorage.setItem('DOCNAME',user.account)
    doctoken.value=res.data.data.token
    alert('登陆成功')
    // 登录连接socket
    handleMessage()

    if(res.data.data.isFirst){
      vis_change.value=true
    }
    // console.log(res)
    if(res.data.code){
      res=await reqCurrentNum(did)
      cur_morning.value=res.data.data.nowAmNum
      cur_afternoon.value=res.data.data.nowPmNum
    }
  }else{
    alert(`${res.data.msg}`)
  }
}

// 收集新密码
let user_reset=reactive({
  password:'',
  confirm:''
})

let form_reset=ref()

// 校验
let rules_reset={
  password:[{trigger:'blur'},
  {validator:validatePassword,trigger:'blur'}],

  confirm:[{trigger:'blur'},
  {validator:(rule, value, callback)=>{
    if(!user_reset.confirm){
      callback(new Error('请确认密码'))
    }else if(user_reset.confirm!=user_reset.password){
      callback(new Error('密码不一致'))
    }else{
      callback()
    }
  },trigger:'blur'}
  ]
}

// 点击重置密码
const changePassword=async ()=>{
  await form_reset.value.validate()
  let res=await reqdocReset(localStorage.getItem('DOCTORID'),user_reset.confirm)
  // console.log(res)
  console.log(localStorage.getItem('DOCTORID'),user_reset.confirm)
  if(res.data.code){
    vis_reset.value=false
    localStorage.clear()
    window.location.href = '/doctor';
    alert('重置成功')
  }
}

// 设置预约人数
const handleChange=async ()=>{
  const did=localStorage.getItem('DOCTORID')
  if(!doctoken.value){
    alert('请先登录')
    return 
  }
  // console.log(did,num_morning.value,num_afternoon.value)
  let res=await reqhandleChange(did,num_morning.value,num_afternoon.value)
  const people={am:num_morning.value,pm:num_afternoon.value}
  localStorage.setItem('PEOPLE',JSON.stringify(people))
  // console.log(res)
  if(res.data.code){
    alert('设置成功')
  }
}

// 医生返回首页弹出框
let vis_doc=ref(false)
const confirm=()=>{
  localStorage.clear()
  $router.push('/home')
}

</script>

<style lang="scss" scoped>
.root{
  min-width: 1810px;
  // height: 1080px;
  background-color: #f2f2f2;
  .top{
    width: 100%;
    height: 100px;
    display: flex;
    align-items: center;
    background: linear-gradient(#41cad1,40%,#f2f2f2);
    .image{
      margin-left:70px;
      margin-top: 20px;
      img{
        width: 80px;
        height: 80px;
      }
    }
    .font{
      width: 1000px;
      margin-top: 20px;
      margin-left: 60px;
      margin-bottom: 10px;
      color: #fff;
      .font2{
        margin-left: -40px;
        font-size: 48px;
        font-weight: 600;
      }
      .font3{
        margin-top: 40px;
        margin-left: 60px;
        font-size: 24px;
        font-weight: 550;
        color: #0984e3;
      }
      .font4{
        margin-top: 40px;
        margin-left: 60px;
        font-size: 24px;
        font-weight: 550;
      }
      .font3:hover{
        cursor: pointer;
        color: #0984e3;
      }
      .font4:hover{
        cursor: pointer;
        color: #0984e3;
      }
    }
    .login{
      min-width: 220px;
      color: #fff;
      margin-top: 20px;
      font-size: 24px;
      font-weight: 800;
      margin-right: 120px;
    }
    .login-hover{
      margin-left: 10px;
    }
    .login-hover:hover{
      cursor: pointer;
      color: #c0c0c0;
    }
  }
  .mid{
    width: 900px;
    height: 200px;
    margin-top: 20px;
    margin-left: 400px;
    .content{
      height: 150px;
      display: flex;
      flex-direction: column;
      font-size: 20px;
      text-align: center;
      .morning{
        margin-top: 30px;
      }
    }
  }
}
.user{
    display: flex;
    height: 60px;
    .user-account{
      font-size: 18px;
      margin-top: 10px;
      margin-right: 40px;
    }
    .user-sex{
      height: 50px;
      font-size: 18px;
      margin-top: 10px;
      margin-right: 40px;
    }
    .input{
      height:50px;
      line-height: 50px;
    }
}
</style>
